//
//  CZStatusViewModel.swift
//  CZWeibo
//
//  Created by 左凯旭 on 16/8/13.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZStatusViewModel: NSObject {
    
    lazy var dataArray:[CZStatusUserViewModel] = [CZStatusUserViewModel]()
  
    
}

extension CZStatusViewModel{
    
    //请求首页数据 isPullUp 是否是上拉加载更多
    
    func loadData(isPullUp: Bool, finish:(isSuccess: Bool)->()){
        
        
        var sinceId: Int64 = 0
        var maxId:Int64 = 0
        //上拉加载更多
        if isPullUp {
            maxId = dataArray.last?.statusModel?.id ?? 0
            if maxId > 0 {
                 // 则返回ID小于或等于max_id的微博，默认为0。
                maxId -= 1
            }
            
        }else{
            //下拉刷新
            sinceId = dataArray.first?.statusModel?.id ?? 0
        }
        
        
        CZNetWorkingTools.sharedTools.loadHomeData(sinceId, maxId: maxId, succes: { (response) in
//            print("请求成功:\(response)")
            //判断是否为nil
            guard let res = response?["statuses"] as? [[String:AnyObject]] else{
                finish(isSuccess: false)
                return
            }
            
            //创建可变数组
            var tmpArray:[CZStatusUserViewModel] = [CZStatusUserViewModel]()
            
            //遍历数组，添加到模型中
            for dic in res{
                
                let statuses = CZStatusModel(dict: dic)
                let statusUserViewModel = CZStatusUserViewModel(statusModel: statuses)
                
                
                //添加模型
                tmpArray.append(statusUserViewModel)
            }
            //赋值
//            self.dataArray = tmpArray
            //上拉
            if isPullUp{
                self.dataArray = self.dataArray + tmpArray
            }else{
                //下拉
                self.dataArray = tmpArray + self.dataArray
            }
     
            
            finish(isSuccess: true)
//            print(self.dataArray.count)
            

            }) { (error) in
                finish(isSuccess: false)
                print("请求失败:\(error)")
        }
        

     
    }
    
}


